package com.example.ts_app_dart.plugins.custom_view

import android.content.Context
import android.graphics.Color
import android.text.Layout
import android.view.Gravity
import android.view.View
import android.widget.TextView
import android.widget.Toast
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView

class CustomView(
    private val context: Context,
    messenger: BinaryMessenger,
    val viewId: Int,
    args: Map<String, Any>?
) : PlatformView, MethodChannel.MethodCallHandler {
    private var customView: CustomFrame? = null
    private val textView: TextView
    private var methodChannel: MethodChannel =
        MethodChannel(messenger, "com.example/custom_channel_view")

    init {
        methodChannel!!.setMethodCallHandler(this)

        textView = TextView(context).apply {
            text = "我是来自Android的原生TextView"
        }
        textView.setOnClickListener {
            Toast.makeText(context, "Method Click NativeToast", Toast.LENGTH_SHORT).show()
            methodChannel!!.invokeMethod("method_click", "=== Channel Params ===")
        }

        println(args);
        println("This is CustomView Created")
    }

    private fun initCustomView(): View {
        if (customView == null) {
            customView = CustomFrame(context, null)
            customView!!.setOnKeyEventCallback(object : OnKeyEventCallback {
                override fun onKeyEventCallback(message: String) {
                    // 将 Android 层的数据传递到 flutter 层 - "native - $message"
                    methodChannel.invokeMethod(
                        "sendMessageFromPlatform",
                        mapOf<String, Any>(
                            Pair("key1", "value1"),
                            Pair("key2", "value2"),
                            Pair("key3", 20389012),
                        ).toString()
                    )
                }
            })
        }
        return customView!!
    }

    override fun getView(): View? {
        // return  textView!!
        return initCustomView()
    }

    override fun dispose() {
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        println("Not yet implemented, " + call.method.toString())
        if (call.method.equals("setPlatformView")) {
            customView?.getMessageFromFlutter(call.arguments.toString())
        } else {
            result.notImplemented()
        }
    }
}